import {inject} from "@angular/core";
import {AuthService} from "../../services/auth.service";
import {
  ActivatedRouteSnapshot,
  CanActivate, CanActivateChildFn,
  CanActivateFn, CanDeactivateFn,
  Router,
  RouterStateSnapshot,
  UrlTree
} from "@angular/router";
import {pathConstant} from "../../data/coommon/Constant";
import {LogService} from "../../services/log-service.service";
import {LocalStorageService} from "../../services/local-storage.service";
import {Observable} from "rxjs";

export const authGuard = () => {
  console.log('authGuard#canActivate called');
  return true;
};


export const authGuard2 = () => {
  // 依赖注入服务
  const authService = inject(AuthService);
  const router = inject(Router);
  // 判断登录
  if (authService.isLogin()) {
    return true;
  }

  //重定向到登录页
  // return router.parseUrl('/login');
  return router.navigateByUrl(pathConstant.path.login);
}

// 判断是管理员
export const canAdmin: CanActivateFn =
  (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
    console.log(state)
    console.log("请求的url = " + state.url)
    return inject(AuthService).isAdmin(inject(LocalStorageService).get('userName'), route.params['id']);
  };

export const canAdmin2:CanActivateChildFn =  (childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
  return false;
}

// export const canActivate3:CanDeactivateFn<T> = (component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => {
//   return Observable.of(this);
// }

export class AuthGuard implements CanActivate {
  private authService: AuthService = inject(AuthService);
  private router: Router = inject(Router);

  constructor() {
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): true | UrlTree {
    const url: string = state.url; // 将要跳转的路径
    return this.checkLogin(url);
  }

  private checkLogin(url: string): true | UrlTree {


    // 已经登录，直接返回true
    if (this.authService.isLogin()) {
      return true;
    }
    // 修改登陆后重定向的地址
    this.authService.redirectUrl = url;
    // 重定向到登录页面
    return this.router.parseUrl(pathConstant.path.login);
  }
}
